<?php

namespace app\modules\Product\models;

use Yii;
use app\modules\Customer\models\Customer;
use app\modules\Customer\models\CustomerContact;
use app\modules\Cost\models\Cost;
use app\modules\Manage\models\User;
use app\modules\Income\models\IncomeClaim;
use app\modules\Basic\models\CityCode;
/**
 * This is the model class for table "product".
 *
 * @property int $id
 * @property int $customer_id 客户ID
 * @property string $name 团名称
 * @property string $code 团号
 * @property string $p_name 联系人姓名
 * @property string $p_phone 联系人电话
 * @property string $p_mail 联系人邮箱
 * @property string $p_department 联系人部门
 * @property string $city 目的地城市(多个)
 * @property string $begin_date 抵达日期
 * @property string $end_date 离开日期
 * @property int $num 团人数
 * @property string $colse_date 关团时间
 * @property int $status 1 报价 2成团 3执行 4关团 10取消
 * @property int $user_id 创建人ID
 * @property string $oper_id 指定操作ID(多个)
 * @property int $currency 货币(美元)
 * @property string $price 总收入
 * @property string $cost_price 总成本
 * @property string $file_path 第一次报价单
 * @property string $created_at 创建时间
 * @property string $updated_at
 */
class Product extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'product';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['customer_id', 'num', 'status', 'user_id', 'currency','product_type'], 'integer'],
            [['customer_id'], 'required'],
            [['begin_date', 'city','oper_id','end_date', 'colse_date', 'created_at', 'updated_at'], 'safe'],
            [['price', 'cost_price'], 'number'],
            [['name', 'code','customer_code'], 'string', 'max' => 255],
            [['p_name', 'p_phone', 'p_mail', 'p_department'], 'string', 'max' => 128],
            [['remark'], 'string', 'max' => 1024],
        ];
    }

    //保存前处理
    public function beforeSave($insert) {//{{{

        if($insert){

            $this->created_at = date("Y-m-d H:i:s");
            $this->user_id    = Yii::$app->user->id;
        }
        return parent::beforeSave($insert);

    }//}}}

    // 保存后处理
    public function afterSave($insert, $changedAttributes){//{{{
        
        parent::afterSave($insert, $changedAttributes);    
            
        $ret = CustomerContact::find()->where(['customer_id'=>$this->customer_id,'p_name'=>$this->p_name, 'p_phone'=>$this->p_phone])->one();

        if($ret){

            $ret->p_name = $this->p_name;
            $ret->p_phone = $this->p_phone;
            $ret->p_mail = $this->p_mail;
            $ret->p_department = $this->p_department;
            $ret->save();

        }else{

            $model = new CustomerContact();
            $model->product_id = $this->id;
            $model->customer_id = $this->customer_id;
            $model->p_name = $this->p_name;
            $model->p_phone  = $this->p_phone;
            $model->p_mail = $this->p_mail;
            $model->p_department = $this->p_department;

            $model->save(); 
        }

      
    }//}}}

    //获取本人创建的团队
    public static function selfAll(){
        $model = Product::find()->where(['user_id'=>\yii::$app->user->id])->all();
        return $model;
    }

    //汇款总手续费
    public function getProPrice(){
        $pro_price = IncomeClaim::find()->where(['product_id'=>$this->id,'status'=>2])->sum('pro_price');
        return $pro_price ? round($pro_price,2) : 0;
    }
    //实际总收入
    public function getRealPrice(){
        $real_price = $this->price - $this->getProPrice();

        return $real_price ? round($real_price,2) : 0;
    }

    //获取成本项总金额
    public function getCostPrice(){
        $price = Cost::find()->where(['product_id'=>$this->id,'status'=>1])->sum('price');
        return $price ? round($price,2) : 0;
    }


    //获取成本剩余成本项金额
    public function getSurPrice(){
        $price = $this->price - $this->getCostPrice();
        return $price ? round($price,2) : 0;
    }

    //毛利
    public function getProfitPrice(){
        $price = $this->price - $this->getCostPrice();
        return $price ? round($price,2) : 0;
    }

    //毛利率
    public function getProfit(){
        $profit = 0;
        if($this->price > 0){
            $profit = ($this->getProfitPrice() / $this->price) * 100;
        }
        $profit = ($profit ? round($profit,2) : 0).'%';
        return $profit;
    }

    //获取上传报价单
    public function getLog(){
        return $this->hasMany(ProductLog::className(), ['product_id' => 'id']);
    }

    //获取没有删除的报价单
    public function getAllLogs(){
        $log = ProductLog::find()->where(['product_id'=>$this->id,'status'=>1])->orderBy('created_at desc')->all();
        return $log;
    }

    //获取上传报价单次数
    public function getLogNum(){
        $num = ProductLog::find()->where(['product_id'=>$this->id,'status'=>1])->count();
        return $num;
    }

    //  获取客户信息
    public function getCustomer(){
        return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
    }

    //获取我自己的成本项
    public function getMyCost(){
        $cost = Cost::find()->where(['product_id'=>$this->id,'status'=>1,'user_id'=>\yii::$app->user->id])->all();
        return $cost;
    }

    //获取我自己的成本项
    public function getDelCost(){
        $cost = Cost::find()->where(['product_id'=>$this->id,'status'=>2])->all();
        return $cost;
    }

    //获取其他人的成本项
    public function getOtherCost(){
        $cost = Cost::find()->where(['product_id'=>$this->id,'status'=>1])->andWhere(['!=','user_id',\yii::$app->user->id])->all();
        return $cost;
    }

    //获取销售（开团人）
    public function getUserName(){
        $user = User::findOne($this->user_id);
        return $user ? $user->name : ' ';
    }

    //指定操作 人员
    public function getOperName(){
        $oper_str = '';
        if($this->oper_id){
            $oper_id = json_decode($this->oper_id);
            foreach($oper_id as $c){
                $user_m = User::findOne($c);
                if($user_m){
                    $oper_str .= $user_m->name.' / ';
                }
                
            }
        }
        return $oper_str;
    }

    //获取城市
    public function getCityInfo(){
        $city_str = '';
        if($this->city){
            $city = json_decode($this->city);
            if(is_array($city)){
                foreach($city as $c){
                    $city_m = CityCode::find()->where(['code'=>$c])->one();
                    if($city_m){
                        $city_str .= $city_m->code.'-'.$city_m->zh_name.' / ';
                    }
                    
                }
            }
            
        }
        return $city_str;
    }

    //获取已收金额
    public function getIncomePrice(){
        $price = IncomeClaim::find()->where(['product_id'=>$this->id,'status'=>2])->sum('price');
        return $price ? $price : 0;
    }


    //获取 预计到款日期
    public function getPayDate(){
        $model = Invoice::find()->where(['product_id'=>$this->id])->orderBy('payment_date desc')->one();
        return $model;
    }

    //获取 逾期时间
    public function getOverdueTime(){
        $day = '';
        $price = $this->price - $this->incomePrice;
        if( $price > 0){ //还有未收款
            $date = date("Y-m-d",time());
            $invoice = $this->getPayDate();
            if($invoice){ //获取 预计到款日期
               $send1 = strtotime($date);
               $send2 = strtotime($invoice->payment_date);
               if($send1 > $send2){
                  $day = ($send1 - $send2) / 86400 . '天';
                  return $day;
               } 
            }
            return $day;
        }
        return $day;
    }

    //获取团组所使用的酒店品牌和金额
    public function getHotelGroupName(){
        $cost = Cost::find()->where(['product_id'=>$this->id,'status'=>1])->all();
        $hotel_name = '';
        $hotel_name_arr = [];
        if($cost){
            foreach($cost as $c){
                if($c->supplier){
                    if(floatval($c->supplier->hotel_group) != 0){

                        $hotel_name_arr[$c->supplier->hotel_group]['name'] = $c->supplier->enBrand;
                        $hotel_name_arr[$c->supplier->hotel_group]['price'][] = $c->price; 
                    }
                }
                
            }
        }

        // if($hotel_name_arr){
        //     $hotel_name = implode("/",array_unique($hotel_name_arr));
        // }

        return $hotel_name_arr;
    }
    
    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'customer_id' => Yii::t('app.product', 'Customer ID'),
            'customer_code' => Yii::t('app.product', 'Customer Code'),
            'product_type' => Yii::t('app.product', 'Product Type'),
            'name' => Yii::t('app.product', 'Name'),
            'code' => Yii::t('app.product', 'Code'),
            'p_name' => Yii::t('app.product', 'P Name'),
            'p_phone' => Yii::t('app.product', 'P Phone'),
            'p_mail' => Yii::t('app.product', 'P Mail'),
            'p_department' => Yii::t('app.product', 'P Department'),
            'city' => Yii::t('app.product', 'City'),
            'begin_date' => Yii::t('app.product', 'Begin Date'),
            'end_date' => Yii::t('app.product', 'End Date'),
            'num' => Yii::t('app.product', 'Num'),
            'colse_date' => Yii::t('app.product', 'Colse Date'),
            'status' => Yii::t('app', 'Status'),
            'user_id' => Yii::t('app.product', 'User ID'),
            'oper_id' => Yii::t('app.product', 'Oper ID'),
            'currency' => Yii::t('app', 'Currency'),
            'price' => Yii::t('app.product', 'Price'),
            'cost_price' => Yii::t('app.product', 'Cost Price'),
            'remark' => Yii::t('app.product', 'Remark'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
        ];
    }
}
